import mongooes from 'mongoose'

const UserSchema = new mongooes.Schema({
  username: { type: String, required: true },
  email: { type: String, required: true },
  authentication: {
    password: { type: String, required: true, select: false },
    salt: { type: String, select: false },
    sessionToken: { type: String, select: false }
  },
})

export const UserModel = mongooes.model('User', UserSchema)

export const getUsers = async () => {
  return await UserModel.find()
}

export const getUserEmail = async (email: string) => UserModel.findOne({ email }).select('+authentication.salt +authentication.password')  // findOneAndDelete is a mongoose method

export const getUserBysessionToken = async (sessionToken: string) => UserModel.findOne({ 'authentication.sessionToken': sessionToken })

export const getUserById = (id: string) => UserModel.findById(id)
export const createUser = (values: Record<string, any>) => new UserModel(values).save().then((user) => user.toObject())
export const deleteUserById = (id: string) => UserModel.findByIdAndDelete({ _id: id })
export const updateUserbyId = (id: string, values: Record<string, any>) => UserModel.findByIdAndDelete(id, values)